package com.axter.libs.photo.previewphoto;

import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;

import com.axter.libs.photo.ImageLoaderCache;
import com.axter.libs.photo.R;
import com.axter.libs.photo.display.LoadingListener;
import com.axter.libs.photo.display.LoadingProgressListener;
import com.nostra13.universalimageloader.core.assist.FailReason;

import java.io.FileDescriptor;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.List;

import pl.droidsonroids.gif.GifDrawable;
import pl.droidsonroids.gif.MultiCallback;
import uk.co.senab.photoview.PhotoView;
import uk.co.senab.photoview.PhotoViewAttacher;

/**
 * @author axter
 */
public class PreviewPhotoAdapter extends PagerAdapter implements View.OnClickListener {
    public PhotoViewAttacher.OnPhotoTapListener photoTapListener;
    private ArrayList<String> paths;
    private List<PhotoViewProgress> views = new ArrayList<>(4);
    private ViewGroup mContainer;
    private MultiCallback multiCallback = new MultiCallback();

    public PreviewPhotoAdapter(PhotoViewAttacher.OnPhotoTapListener photoTapListener, ArrayList<String> paths) {
        this.photoTapListener = photoTapListener;
        this.paths = paths;
    }

    @Override
    public int getCount() {
        return paths == null ? 0 : paths.size();
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == object;
    }

    private PhotoViewProgress getPhotoView() {
        for (PhotoViewProgress view : views) {
            if (view.getParent() == null) {
                views.remove(view);
                return view;
            }
        }
        return null;
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        if (mContainer == null)
            mContainer = container;
        PhotoViewProgress photoView = getPhotoView();
        if (photoView == null) {
            photoView = new PhotoViewProgress(container.getContext().getApplicationContext());
        } else {
            photoView.setImageDrawable(null);
        }
        container.addView(photoView);

        photoView.setOnPhotoTapListener(photoTapListener);
        photoView.setOnClickListener(this);
        photoView.setTag(position);
        ImageLoaderCache.displayUrl(paths.get(position), photoView, loadingListener, progressListener);

        return photoView;
    }

    public LoadingListener loadingListener = new LoadingListener() {
        @Override
        public void onLoadingStarted(String imageUri, View view) {
            PhotoViewProgress photo = (PhotoViewProgress) view;
            photo.showTip(view.getContext().getString(R.string.photoselect_loading));
        }

        @Override
        public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
            PhotoViewProgress photo = (PhotoViewProgress) view;
            photo.showTip(view.getContext().getString(R.string.photoselect_load_fail));
        }

        @Override
        public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
            PhotoViewProgress photo = (PhotoViewProgress) view;
            photo.hideTip();
            if (imageUri.endsWith("gif")) {
                String localPath = ImageLoaderCache.getLocalPath(imageUri);
                try {
                    // 加载完处理gif
                    FileDescriptor fd = new RandomAccessFile(localPath, "r").getFD();
                    GifDrawable gifDrawable = new GifDrawable(fd);
                    photo.setImageDrawable(gifDrawable);
                    multiCallback.addView(photo);
                    gifDrawable.setCallback(multiCallback);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        @Override
        public void onLoadingCancelled(String imageUri, View view) {
            PhotoViewProgress photo = (PhotoViewProgress) view;
            photo.hideTip();
        }
    };

    public LoadingProgressListener progressListener = new LoadingProgressListener() {
        @Override
        public void onProgressUpdate(String imageUri, View view, int current, int total) {
            PhotoViewProgress photo = (PhotoViewProgress) view;
            if (current > total || total == 0) {
                photo.showTip(view.getContext().getString(R.string.photoselect_downing));
            } else {
                photo.showTip(current * 100 / total + "%");
            }
        }
    };

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView((View) object);
        if (!views.contains(object)) {
            views.add((PhotoViewProgress) object);
            Drawable drawable = ((PhotoViewProgress) object).getDrawable();
            if (drawable == null) {
                return;
            }
            if (drawable instanceof GifDrawable) {
                ((GifDrawable) drawable).stop();
                ((GifDrawable) drawable).recycle();
                ((PhotoViewProgress) object).setImageDrawable(null);
            } else if (drawable instanceof BitmapDrawable) {
                ((PhotoViewProgress) object).setImageDrawable(null);
            }
        }
    }

    public void remove(int position) {
        paths.remove(position);
        notifyDataSetChanged();
        for (int i = mContainer.getChildCount() - 1; i >= 0; i--) {
            PhotoViewProgress child = (PhotoViewProgress) mContainer.getChildAt(i);
            Object tag = child.getTag();
            if (tag == null) {
                continue;
            }
            int ti = (int) tag;
            if (ti >= paths.size()) {
                mContainer.removeView(child);
                views.add(child);
            } else {
                update(child, ti);
            }
        }
    }

    public void update(PhotoView photoView, int position) {
        photoView.setTag(position);

        ImageLoaderCache.displayUrl(paths.get(position), photoView, loadingListener, progressListener);
    }

    public static PhotoView getView(ViewPager viewPager, int position) {
        int count = viewPager.getChildCount();
        for (int i = 0; i < count; i++) {
            PhotoView view = (PhotoView) viewPager.getChildAt(i);
            if ((int) (view.getTag()) == position) {
                return view;
            }
        }
        return null;
    }

    @Override
    public void onClick(View view) {
        if (photoTapListener != null)
            photoTapListener.onPhotoTap(view, 0, 0);
    }

    @Override
    public int getItemPosition(Object object) {
        return POSITION_NONE;
    }
}
